use std::{
    env, fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};
//服务端获取请求与响应
fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&stream);
    let request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();
    println!("服务端请求内容:{}", request.split_first().unwrap().0);
    // 以不同于其它请求的方式处理 / 请求
    // let (status_line, filename) = if request[0] == "GET / HTTP/1.1" {
    //     // let (status_line, filename) = if request[0].starts_with("GET") {
    //     ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
    // } else {
    //     ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    // };
    // 1.在当前server实现慢请求
    let (status_line, filename) = match (request.split_first().unwrap().0).as_str() {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK\r\n\r\n", "index.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK\r\n\r\n", "sleep.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html"),
    };
    let contents = fs::read_to_string(filename).unwrap();
    let response = format!("{}{}", status_line, contents);
    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
//获取自定义端口号
fn get_port() -> u16 {
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 {
        args[1].parse().expect("不是有效的端口号")
    } else {
        8080
    }
}
// 3.引入线程池
use web_srv_multi::ThreadPool;
fn main() {
    //获取自定义端口
    let port: u16 = get_port();
    // Tcp服务绑定
    // let listener = TcpListener::bind(("0.0.0.0", port)).unwrap();
    let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
    // 3.创建线程池

    let pool = ThreadPool::new(4);
    // 获取到传入的Tcp流
    // for stream in listener.incoming() {
    // 10.当recv返回错误时显式退出循环
    // for stream in listener.incoming().take(3) { //优雅停机
    for stream in listener.incoming() {
        let stream = stream.unwrap();
        // 1.在当前server实现慢请求
        // handle_connection(stream);
        // 2.为每个请求分配线程
        // thread::spawn(|| {
        //     handle_connection(stream);
        // });
        // 3.创建线程池,引入lib库
        pool.execute(|| {
            println!(
                "Connection from {} established",
                stream.peer_addr().unwrap()
            );
            handle_connection(stream);
        });
    }
}
